package com.md.mymusic.db;

import android.text.TextUtils;
import com.md.basedpc.persistence.PHDbUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyue
 * created 2021/3/16
 * desc 自建专辑的增删改查
 */
public class AlbumDBManager {

    /**
     * 查询所有自建的专辑
     */
    public static List<SelfCreatedAlbumDB> getAllSelfAlbums(){
        String where = " 1=1 ";
        List<SelfCreatedAlbumDB> dbs = new ArrayList<>();
        try {
            dbs = PHDbUtils.getInstance().query(SelfCreatedAlbumDB.class, where);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dbs;
    }


    /***
     * 批量保存 音频
     * @param albumDB
     * @param audioList
     */
    public static void saveAudioList(SelfCreatedAlbumDB albumDB, List<SelfSaveAudioDB> audioList) {
        saveAlbum(albumDB);
        for (SelfSaveAudioDB audioDB : audioList) {
            saveAudio(albumDB.getId(), audioDB);
        }
    }

    /**
     * 保存 专辑信息
     * @param albumDB
     * @return
     */
    private static SelfCreatedAlbumDB saveAlbum(SelfCreatedAlbumDB albumDB) {
        String where = " 1=1 ";
        if (!TextUtils.isEmpty(albumDB.getId()))
            where += " and id=" + albumDB.getId() + "";
        try {
            List<SelfCreatedAlbumDB> dbs = PHDbUtils.getInstance().query(SelfCreatedAlbumDB.class, where);
            if (dbs == null || dbs.size() == 0) {
                PHDbUtils.getInstance().insert(albumDB);
            } else {
                return dbs.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存 音频信息
     * @param audioDB
     */
    private static SelfSaveAudioDB saveAudio(String albumId, SelfSaveAudioDB audioDB) {
        audioDB.setAlbum_id(albumId);
        String where = " 1=1 ";
        if (!TextUtils.isEmpty(audioDB.getId()))
            where += " and id=" + audioDB.getId() + "";
        if (!TextUtils.isEmpty(albumId))
            where += " and album_id=" + albumId + "";
        try {
            List<SelfSaveAudioDB> dbs = PHDbUtils.getInstance().query(SelfSaveAudioDB.class, where);
            if (dbs == null || dbs.size() == 0) {
                PHDbUtils.getInstance().insert(audioDB);
            } else {
                return dbs.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除 音频信息
     * @param audioId
     * @return
     */
    public static boolean deleteAudio(String audioId) {
        boolean isDelSucess = false;
        String where = " 1=1 ";
        if (!TextUtils.isEmpty(audioId))
            where += " and id=" + audioId + "";
        try {
            isDelSucess = PHDbUtils.getInstance().delete(SelfSaveAudioDB.class, where);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isDelSucess;
    }
}
